package com.slmxz.tms.document.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.slmxz.tms.common.base.IBaseEnum;
import com.slmxz.tms.common.component.PrimaryKeyGeneratorService;
import com.slmxz.tms.common.component.RedisUserService;
import com.slmxz.tms.common.constant.SystemConstants;
import com.slmxz.tms.common.enums.BizMessageEnum;
import com.slmxz.tms.common.enums.TableEnum;
import com.slmxz.tms.common.model.Option;
import com.slmxz.tms.core.exception.Asserts;
import com.slmxz.tms.core.exception.BizException;
import com.slmxz.tms.common.result.ResultCode;
import com.slmxz.tms.core.service.DataScopeService;
import com.slmxz.tms.core.service.PrimaryKeySerivce;
import com.slmxz.tms.document.enums.DriverLicenseTypeEnum;
import com.slmxz.tms.document.enums.DriverTypeEnum;
import com.slmxz.tms.document.mapper.ContractorDriverMapper;
import com.slmxz.tms.document.mapper.ContractorMapper;
import com.slmxz.tms.document.mapper.DriverMapper;
import com.slmxz.tms.document.model.entity.Contractor;
import com.slmxz.tms.document.model.entity.ContractorDriver;
import com.slmxz.tms.document.model.entity.Driver;
import com.slmxz.tms.document.model.vo.ContractorDriverVO;
import com.slmxz.tms.document.model.vo.DriverVO;
import com.slmxz.tms.document.service.DriverService;
import com.slmxz.tms.system.model.vo.UserInfoVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 司机信息服务实现类
 * @author sunyao
 * @Date 2024-11-08
 */
@Service
@RequiredArgsConstructor
public class DriverServiceImpl extends ServiceImpl<DriverMapper, Driver> implements PrimaryKeySerivce<Driver>, DriverService, DataScopeService<Driver> {

    private final ContractorDriverMapper contractorDriverMapper;
    private final ContractorMapper contractorMapper;
    /**
    * 获取司机信息分页列表
    * @return {@link IPage< DriverVO >} 司机信息分页列表
    */
    @Override
    public IPage<DriverVO> selectDriverPage(IPage<DriverVO> page,DriverVO driver) {
        UserInfoVO user = RedisUserService.currentUser();
        try{
            this.dataScopeHandler(driver);
        }catch (Exception e){
            driver.setScopeNo(user.getScopeNo());
            driver.setDataOperate(SystemConstants.OPERATE_EQUALS);
        }
        driver.setCompanyId(user.getCompanyId());
        List<DriverVO> drivers = this.baseMapper.selectDriverPage(page,driver);
        if(CollectionUtil.isNotEmpty(drivers)){
            drivers.forEach(item -> {
                item.setDriverTypeLabel(IBaseEnum.getLabelByValue(item.getDriverType(), DriverTypeEnum.class));
                String licenseTypeLabel = IBaseEnum.getLabelByValue(item.getLicenseType(), DriverLicenseTypeEnum.class);
                item.setLicenseTypeLabel(licenseTypeLabel);
            });
        }
        return page.setRecords(drivers);
    }

    @Override
    public List<Option<String>> selectOption(DriverVO driver) {
        return this.baseMapper.selectOption(driver);
    }

    /**
     * @param id 司机信息ID
     * @return
     */
    @Override
    public DriverVO selectDriverDetail(Long id) {
        Driver entity = this.getById(id);
        DriverVO driver = BeanUtil.copyProperties(entity,DriverVO.class);
        //获取司机所属承运商关系
        ContractorDriverVO contractorDriverParam = new ContractorDriverVO();
        contractorDriverParam.setDriverId(id);
        List<ContractorDriverVO> contractorDrivers = this.contractorDriverMapper.selectContractorDriver(contractorDriverParam);
        if(CollectionUtil.isNotEmpty(contractorDrivers)){
            ContractorDriverVO contractorDriver = contractorDrivers.get(0);
            driver.setContractorId(contractorDriver.getContractorId());
            driver.setContractorName(contractorDriver.getContractorName());
        }
        return driver;
    }
    
    /**
     * 新增司机信息
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveDriver(DriverVO driver) throws Exception {
        Long driverId = this.getId();
        driver.setId(driverId);
        //校验选择的承运商数据是否还存在
        long count = this.contractorMapper.selectCount(new QueryWrapper<Contractor>().lambda()
                .eq(Contractor::getId,driver.getContractorId())
                .eq(Contractor::getIsDeleted,0));
        Asserts.fail(count == 0,BizMessageEnum.BIZ0000001);

        ContractorDriver contractorDriver = new ContractorDriver();
        contractorDriver.setContractorId(driver.getContractorId());
        contractorDriver.setDriverId(driverId);
        this.contractorDriverMapper.insert(contractorDriver);
        return this.save(driver);
    }
    
    /**
     * 更新司机信息
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateDriver(DriverVO driver) {
        //校验选择的承运商数据是否还存在
        long count = this.contractorMapper.selectCount(new QueryWrapper<Contractor>()
                .lambda().eq(Contractor::getId,driver.getContractorId())
                .eq(Contractor::getIsDeleted,0));
        Asserts.fail(count == 0,BizMessageEnum.BIZ0000001);

        QueryWrapper<ContractorDriver> contractorDriverQuery = new QueryWrapper<>();
        contractorDriverQuery.lambda().eq(ContractorDriver::getDriverId,driver.getId());
        List<ContractorDriver> contractorDrivers = this.contractorDriverMapper.selectList(contractorDriverQuery);
        if(CollectionUtil.isNotEmpty(contractorDrivers)){
            contractorDrivers.forEach(item -> {
                if(item.getContractorId().equals(driver.getContractorId())){
                    //相等则不需要修改
                    return;
                }
                item.setContractorId(driver.getContractorId());
                this.contractorDriverMapper.updateById(item);
            });
        }
        return this.updateById(driver);
    }
    
    /**
     * 删除司机信息
     *
     * @param ids 司机信息ID，多个以英文逗号(,)分割
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteDrivers(String ids) {
        //请求的参数是空的
        Asserts.fail(StrUtil.isBlank(ids),BizMessageEnum.PARAM_IS_NULL);
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();

        //删除司机对应的承运商关系
        QueryWrapper<ContractorDriver> contractorDriverQuery = new QueryWrapper<>();
        contractorDriverQuery.lambda().in(ContractorDriver::getDriverId,idList);
        this.contractorDriverMapper.delete(contractorDriverQuery);
        return this.removeByIds(idList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean activeOrLogout(DriverVO driver) {
        //激活或者注销业务数据
        Asserts.fail((CollectionUtil.isEmpty(driver.getIds()) || driver.getIsDeleted() == null),BizMessageEnum.PARAM_IS_NULL);

        List<Driver>  driverList = new ArrayList<>(driver.getIds().size());
        driver.getIds().forEach(id -> {
            Driver driverParam = new Driver();
            driverParam.setId(id);
            driverParam.setIsDeleted(driver.getIsDeleted());
            driverList.add(driverParam);
        });
        this.updateBatchById(driverList,10);
        return true;
    }

}
